Pytest
正文
An important point: as well as making sure our code is returning correct answers, we also need to ensure the tests themselves are also correct.
a good rule is to make tests simple enough
============================================== test session starts =================================
platform darwin -- Python 3.11.4, pytest-7.4.3, pluggy-1.3.0
rootdir: /Users/alex/work/SSI/training/lessons/python-intermediate-inflammation
plugins: anyio-4.0.0
collected 2 items
tests/test_models.py .. [100%]
=============================================== 2 passed in 0.79s ==================================
Pytest looks for functions whose names also start with the letters ‘test_’ and runs each one. Notice the .. after our test script:
- If the function completes without an assertion being triggered, we count the test as a success (indicated as
.). - If an assertion fails, or we encounter an error, we count the test as a failure (indicated as
F). The error is included in the output so we can see what went wrong.
有些输入本来就应该触发异常,因此“抛出异常”也可以是正确行为。
代码如下:
import pytest
from inflammation.models import daily_min
def test_daily_min_string():
"""Test for TypeError when passing strings"""
with pytest.raises(TypeError):
daily_min([['Hello', 'there'], ['General', 'Kenobi']])
pytest.raises 的含义
with pytest.raises(TypeError):
daily_min(...)
含义是:
执行
with代码块中的代码,并期待它抛出TypeError。
结果分三种情况:
| 函数行为 | 测试结果 |
|---|---|
抛出 TypeError |
测试通过 |
| 没有抛出异常 | 测试失败 |
抛出其他异常,如 ValueError |
测试失败 |